package com.example.demo.controller;

import java.util.List;
import com.example.demo.bean.Book;
import com.example.demo.bean.User;
import com.example.demo.bean.Comment;
import com.example.demo.bean.Record;
// import com.example.demo.service.BookService;
import com.example.demo.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.interceptor.TokenInterceptor;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.HashMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import org.springframework.core.io.InputStreamResource;
import java.io.FileInputStream;
import org.springframework.http.ResponseEntity;

@RestController
public class BookController {
    public String getTime(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
//    private static String filePath = "/Users/80805361/Documents/springBootProject-master/src/main/resources/static/public/pic/";
    private static String filePath = System.getProperty("user.dir")+"/src/main/resources/static/public/pic/";
    private static Map success = new HashMap<>();
    // Map<String,String> success = new HashMap<>();
    
    // public String setToken(int id, String type){
    //     return Base64.getEncoder().encodeToString((String.valueOf(id)+"-"+type+"-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes());
    // }
    // public String getToken(String token){
    //     String decodedString = new String(Base64.getDecoder().decode(token));
    //     return Base64.getEncoder().encodeToString((String.valueOf(id)+"-"+type+"-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes());
    // }
    @Autowired
    private BookMapper mapper;
    // private BookService service;

    @RequestMapping("/login")
    public Map login(@RequestParam Map<String, String> map){
        User user = mapper.selectUser(map);
        Map success = new HashMap();
        if(user==null){
            String regex = "^1\\d{10}$";
            if(!map.get("username").matches(regex)){
                success.put("code",1);
                success.put("msg","请用手机号登录");
                return success;
            }
            map.put("date", getTime());
            map.put("type", "1");
            map.put("avatar", "default.png");
            map.put("nickname", "小太阳");
            mapper.addUser(map);
            user = mapper.selectUser(map);
            TokenInterceptor.list.add(user.getId());
            success.put("code", 0);
            success.put("msg", "注册成功");
            success.put("token", user.getId());
            success.put("id", user.getId());
            success.put("type", "1");
            success.put("nickname", "小太阳");
            success.put("username", user.getUsername());
            success.put("avatar", "default.png");
            return success;
        }
        if(!user.getPassword().equals(map.get("password"))){
            success.put("code", 1);
            success.put("msg", "密码错误");
            return success;
        }
        if(!TokenInterceptor.list.contains(user.getId())){
            TokenInterceptor.list.add(user.getId());
        }
        success.put("code",0);
        success.put("msg", "登录成功");
        success.put("token", user.getId());
        success.put("id", user.getId());
        success.put("type", user.getType());
        success.put("nickname",  user.getNickname());
        success.put("username", user.getUsername());
        success.put("avatar", user.getAvatar());
        return success;
    }
    @RequestMapping("/create")
    public Book create(Book book){
        book.setStock(book.getTotal());
        book.setDate(getTime());
        mapper.create(book);
        return book;
    }
    @RequestMapping("/deleteBook")
    public Book deleteBook(Book book){
        mapper.deleteBook(book);
        return book;
    }
    @RequestMapping("/deleteComment")
    public Map deleteComment(@RequestParam Map map){
        mapper.deleteComment(map);
        return success;
    }
    @RequestMapping("/update")
    public Book update(Book book){
        mapper.update(book);
        return book;
    }
    @GetMapping("/updateUser")
    public Map updateUser(@RequestParam Map map, @RequestHeader("token") String id){
        map.put("id",id);
        mapper.updateUser(map);
        return success;
    }
    @GetMapping("/updateRecord")
    public Map updateRecord(@RequestParam Map map){
        Integer stock = mapper.getStock(map);
        map.put("stock",stock+1);
        map.put("updateTime",getTime());
        mapper.updateRecord(map);
        return success;
    }
    @GetMapping("/addRecord")
    public Map addRecord(@RequestParam Map map, @RequestHeader("token") String id){
        Integer stock = mapper.getStock(map);
        map.put("stock",stock-1);
        map.put("userId",id);
        map.put("createTime",getTime());
        mapper.addRecord(map);
        return success;
    }
    @GetMapping("/addComment")
    public Map addComment(@RequestParam Map map, @RequestHeader("token") String id){
        map.put("userId",id);
        map.put("date",getTime());
        mapper.addComment(map);
        return success;
    }
    @RequestMapping("/search")
    public Map search(@RequestParam Map map){
        map.put("pageSize",Integer.parseInt(map.get("pageSize").toString()));
        map.put("start",(Integer.parseInt(map.get("current").toString())-1)*Integer.parseInt(map.get("pageSize").toString()));
        Map res = new HashMap<>();
        List<Book> list = mapper.search(map);
        Integer total = mapper.getBookTotal(map);
        res.put("data",list);
        res.put("total",total);
        return res;
    }
    @RequestMapping("/getRecord")
    public Map getRecord(@RequestParam Map map){
        map.put("pageSize",Integer.parseInt(map.get("pageSize").toString()));
        map.put("start",(Integer.parseInt(map.get("current").toString())-1)*Integer.parseInt(map.get("pageSize").toString()));
        Map res = new HashMap<>();
        List<Record> list = mapper.getRecord(map);
        Integer total = mapper.getRecordTotal(map);
        res.put("data",list);
        res.put("total",total);
        return res;
    }
    @RequestMapping("/getRecordId")
    public Map getRecordId(@RequestParam Map map){
        Map res = new HashMap<>();
        List<Integer> list = mapper.getRecordId(map);
        res.put("data",list);
        return res;
    }
    @RequestMapping("/getComment")
    public Map getComment(@RequestParam Map map){
        map.put("pageSize",Integer.parseInt(map.get("pageSize").toString()));
        map.put("start",(Integer.parseInt(map.get("current").toString())-1)*Integer.parseInt(map.get("pageSize").toString()));
        Map res = new HashMap<>();
        List<Comment> list = mapper.getComment(map);
        Integer total = mapper.getCommentTotal(map);
        res.put("data",list);
        res.put("total",total);
        return res;
    }
    @RequestMapping("/getUser")
    public Map getUser(@RequestParam Map map){
        map.put("pageSize",Integer.parseInt(map.get("pageSize").toString()));
        map.put("start",(Integer.parseInt(map.get("current").toString())-1)*Integer.parseInt(map.get("pageSize").toString()));
        Map res = new HashMap<>();
        List<User> list = mapper.getUser(map);
        Integer total = mapper.getUserTotal(map);
        res.put("data",list);
        res.put("total",total);
        return res;
    }
    @PostMapping("/upload")
    public Map upload(@RequestParam("file") MultipartFile file){
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取后缀名
            String path = System.currentTimeMillis()+filename.substring(filename.lastIndexOf("."));
            //设置文件路径
            File dest = new File(filePath+path);
            file.transferTo(dest);
            success.put("code",0);
            success.put("path",path);
            return success;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success;
    }
    @RequestMapping("/public/pic/{path}")
    public ResponseEntity<InputStreamResource> download(@PathVariable String path) throws Exception{
        InputStreamResource isr = new InputStreamResource(new FileInputStream(filePath+path));
        return ResponseEntity.ok().header("Content-Type", "image/png").body(isr);
    }
}
